/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package app.net.server;

import app.net.Client;
import app.net.messages.InputMessage;
import app.net.Message;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.SocketException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * receive input from client and set to loop
 *
 * @author skyr
 */
public class ServerReceiveThread implements Runnable {

    private ServerGameLoop gameLoop;
    private Client client;
    private boolean running = true;
    private ObjectInputStream inputStream;

    public ServerReceiveThread(Client client, ServerGameLoop gameLoop) {
        this.gameLoop = gameLoop;
        this.client = client;
        try {
            inputStream = new ObjectInputStream(client.getSocket().getInputStream());
        } catch (IOException ex) {
            Logger.getLogger(ServerReceiveThread.class.getName()).log(Level.SEVERE, "init input stream fail", ex);
        }
    }

    @Override
    public void run() {
        while (running) {
            try {
                //forward input message to game loop
                Message m = (Message) inputStream.readObject();
                if (m instanceof InputMessage) {
                    gameLoop.setInputMap(client.getId(), (InputMessage) m);
                }
            } catch (SocketException ex) {
                stop();
            } catch (IOException ex) {
                Logger.getLogger(ServerReceiveThread.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(ServerReceiveThread.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public void start() {
        Thread t = new Thread(this);
        t.start();
    }

    public void stop() {
        running = false;
        try {
            inputStream.close();
        } catch (IOException ex) {
            Logger.getLogger(ServerReceiveThread.class.getName()).log(Level.SEVERE, "stream close fail", ex);
        }
    }
}
